import { defineStore } from 'pinia';
import { getToken, removeToken, setToken } from '../utils/token-utils';

//引入请求的类型限制
import type {getUserInfoType,reqLoginType} from "@/api/userInfo"
//引入请求
import {getLoginRequest,getUserInfoRequest ,getLogoutRequest} from '@/api/userInfo'
//引入router
import { staticRoutes,allAsyncRoutes ,allRandomRouters } from "@/router/routes";
import type { RouteRecordRaw } from "vue-router";
import cloneDeep  from 'lodash/cloneDeep';
import router from '@/router';

/**
 * 用户信息
 * @methods setUserInfos 设置用户信息
 */

//定义state里面的类型
export interface UserInfoState{
  token :string;
  userInfo :getUserInfoType;
  menuRoutes:RouteRecordRaw[]
}
//1.过滤动态路由中,需要展示的路由菜单,并收集起来(返回出去)
function allAsyncRouters(allAsyncRoutes:RouteRecordRaw[],routerName:string[]){
    return allAsyncRoutes.filter(item => {
      if(routerName.includes(item.name as string)){
        if(item.children && item.children.length){
          item.children = allAsyncRouters(item.children as RouteRecordRaw[],routerName)
        }
        return true;
      }
      
    })
}

//2.把根据用户信息过滤出来的动态路由数组，和任意路由全部放入静态路由中
function addRoute (routes:RouteRecordRaw[]){
  routes.forEach(item => {
    router.addRoute(item)
  })
}


export const useUserInfoStore = defineStore('userInfo', {

	state: (): UserInfoState => ({
    token: getToken() as string,
    userInfo:{
      routes:[],
      buttons:[],
      roles: [],
      name: "",
      avatar: "",
    },
    menuRoutes: staticRoutes
  }),

	actions: {
    async login (loginParam:reqLoginType) {
      try{
        //发送登录请求
        const re = await getLoginRequest(loginParam);
        //获取token，并设置给state中的token
        this.token = re.token;
        //把token设置在本地存储
        setToken(this.token)
      }catch(e){
        return Promise.reject(e)
      }
    },

    //

    //用户信息请求的方法
    async getInfo () {
      try{
        //发送用户信息请求
        const re = await getUserInfoRequest();
        //把数据交给state
        this.userInfo = re
        const userAsyncRoutes =  allAsyncRouters(cloneDeep(allAsyncRoutes),re.routes);
        //2.把过滤出来的动态路由插入到路由器中
        addRoute(userAsyncRoutes.concat(allRandomRouters))

        //3. 修改静态路由，让菜单栏也进行更新
        this.menuRoutes = staticRoutes.concat(userAsyncRoutes,allRandomRouters)
      }catch(e){
        return Promise.reject(e)
      }
    },

    //退出登入
    async getLogout (){
      try{
        //发送退出登录请求
        await getLogoutRequest();
        //作出清理工作
        this.reset()
        //退出登录的时候，把路由器中的路由全部清理掉
        // 获取所有 路由记录的完整列表
        const routes = router.getRoutes();
        routes.forEach(item => {
          if(item.name){
            router.removeRoute(item.name)
          }
        })
        addRoute(staticRoutes)
      }catch(e){
        return Promise.reject(e) 
      }
    },

    reset () {
      // 删除local中保存的token
      this.token =  ""
      removeToken()
      // 提交重置用户信息的mutation
      this.userInfo = {
        routes:[],
        buttons:[],
        roles: [],
        name: "",
        avatar: "",
      }
    },
	},
});
